package com.gem.talkbase.activity;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import com.gem.talkbase.R;
import com.gem.talkbase.adapter.ContactAddAdapter;
import com.gem.talkbase.adapter.RecentChatAdapter;
import com.gem.talkbase.bean.Contacts;
import com.gem.talkbase.bean.Firend;
import com.gem.talkbase.bean.FirendMsg;
import com.gem.talkbase.client.Client;
import com.gem.talkbase.service.JSON_Countacts;
import com.gem.talkbase.service.JSON_Find_Friend;
import com.gem.talkbase.service.JSON_Friend_info;
import com.gem.talkbase.util.T;

import android.R.integer;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

/**
 *
 */
public class AddFirendActivity extends Activity  implements OnClickListener ,OnItemClickListener {
	ListView txListView   ;
	ImageView backiView;
	private Button button1 ,sosobButton;  //添加联系人
	private Cursor result = null ;	// 既然要查询，查询返回的就是结果
	private ListView contactsList = null ;	// 定义ListView组件
	private List<Map<String,Object>> allContacts = null ;
	SharedPreferences sharedPreferences; //获得登录者的id  
	String requestPath=Client.Firend_ipone;
	String requestPath2=Client.AllContact;
	String requestPath3=Client.Find_Firend;
	List<Contacts> list;
	List<Firend> listfFirends;
	EditText td;
	String u_name,u_image,u_stytle,u_nick,u_xb;
	ContactAddAdapter contactAddAdapter;
	private  List<Contacts> list2 =  new ArrayList<Contacts>();
	private ListView listView;   
	int n=0;
	protected SimpleAdapter simple;  
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);	
		setContentView(R.layout.addfirend);

		init() ;   //初始化控件
		//	fun() ;  //动态加载List，动态显示联系人的姓名和手机号



	}

	//初始化控件
	void  init() {
		button1= (Button) findViewById(R.id.txl_button)  ;
		button1.setOnClickListener(this);
		backiView=(ImageView)findViewById(R.id.left_change_btn);
		backiView.setOnClickListener(this);
		sosobButton=(Button)findViewById(R.id.soso_btn);
		sosobButton.setOnClickListener(this);
		td=(EditText)findViewById(R.id.change_edit);
		// listView=(ListView)findViewById(R.id.txl_listView);
		contactsList = (ListView) findViewById(R.id.txl_listView);
		contactsList.setOnItemClickListener(this);
	}

	//	void fun() {
	//		int max = myContacts() ;    // 获取手机通讯录里的 id ，name 
	//		for(int id=0 ; id< max ; id ++) {
	//    	String contactsId = this.allContacts.get(id).get("_id").toString() ;  //取得联系人的ID 号 ，从1开始
	//		   String phone =  getPhoneNumber(contactsId);
	////		   requestServer(phone) ; 
	//		   if(n==1) {
	//			   allContacts.get(id).put("_yaoqin", "邀请") ;
	//		   }
	//		   else if( n==2) {
	//			   allContacts.get(id).put("_yaoqin", "添加") ;
	//		  }
	//		}
	//		
	//		this.simple = new SimpleAdapter(this, this.allContacts,
	//				R.layout.contacts, new String[] {"_id","name" ,"_yaoqin" }, new int[] {
	//				R.id._id, R.id.name ,R.id._yaoqin  });
	//		this.contactsList.setAdapter(this.simple) ;
	//	}
	
	
	public void fun(String userid){
		AjaxParams params = new AjaxParams();
		params.put("login_id", userid);
		FinalHttp fh = new FinalHttp();
		fh.post(requestPath2, params, new AjaxCallBack<String>() {
			@Override
			public void onFailure(Throwable t, String strMsg) {
				System.out.println("加载失败！！！");
				super.onFailure(t, strMsg);
			}
			@Override
			public void onLoading(long count, long current) {  
				// TODO Auto-generated method stub
				System.out.println("正在加载！！！");
				super.onLoading(count, current);
			}

			@Override  
			public void onSuccess(String jsonString) {
				super.onSuccess(jsonString);
			
				list=new ArrayList<Contacts>();
				JSON_Countacts json_Countacts=new JSON_Countacts();
				list=json_Countacts.info(jsonString);
				Iterator<Contacts> iterator=list.iterator();	
				String lxr_id = null,lxr_tj = null ,lxr_name;
				while (iterator.hasNext()) {
					Contacts contacts = (Contacts) iterator.next();
					lxr_id=contacts.get_id_lxr();
					lxr_tj=contacts.get_tj_lxr();
					lxr_name=contacts.getLxr_name();
					Contacts contacts2=new Contacts(lxr_id,lxr_name,lxr_tj);
					list2.add(contacts2);
				}
				contactAddAdapter=new ContactAddAdapter(AddFirendActivity.this,list2);
				contactsList.setAdapter(contactAddAdapter);
				contactAddAdapter.notifyDataSetChanged(); 
			}
		});
	}

	public void info(String uid,String userid){
		AjaxParams params = new AjaxParams();
		params.put("u_id", uid);
		params.put("f_id", userid);
		FinalHttp fh = new FinalHttp();
		fh.post(requestPath3, params, new AjaxCallBack<String>() {
			@Override
			public void onFailure(Throwable t, String strMsg) {
				System.out.println("加载失败！！！");
				super.onFailure(t, strMsg);
			}
			@Override
			public void onLoading(long count, long current) {  
				// TODO Auto-generated method stub
				System.out.println("正在加载！！！");
				super.onLoading(count, current);  
			}

			@Override  
			public void onSuccess(String jsonString) {
				super.onSuccess(jsonString);
				System.out.println(jsonString+"==============好友jsonString");
            if (jsonString.length()==2) {  
            		T.showLong(AddFirendActivity.this, "用户不存在！！");
            }else if(jsonString.length()==3){	
            	    T.showLong(AddFirendActivity.this, "此好友已经存在！请重新添加新朋友！");
			}else {
				listfFirends=new ArrayList<Firend>();
				JSON_Find_Friend json_Find_Friend=new JSON_Find_Friend();
				listfFirends=json_Find_Friend.info(jsonString);
				Iterator<Firend> iterator=listfFirends.iterator();
				Firend firend = null;
				while(iterator.hasNext()){ 
					firend=iterator.next();
					u_name=firend.getUsername();
					u_nick=firend.getUnick();
					u_xb=firend.getUxb();
					u_stytle=firend.getUstyle();
					u_image=firend.getUimage();
					System.out.println(u_name+"====="+u_nick+"====="+u_xb+"====="+u_stytle+"====="+u_image);
					Intent intent =new Intent(AddFirendActivity.this,SerchmanActivity.class);
					intent.putExtra("u_name",u_name);
					intent.putExtra("u_nick",u_nick);
					intent.putExtra("u_xb",u_xb);
					intent.putExtra("u_stytle",u_stytle);
					intent.putExtra("u_image",u_image);
					startActivity(intent);
		
				} 
			}
			}
		});
		
	}
	@Override
	public void onClick(View v) {
		switch ( v.getId())  {
		case R.id.txl_button : 
			//	myContacts() ;
			requestServer() ;
			sharedPreferences =getSharedPreferences(Client.SAVE_USER,MODE_PRIVATE);//获得登录者的信息
			String userid = sharedPreferences.getString("userid", ""); 	
			fun(userid);
			break;
		case R.id.soso_btn:
			String  soso = AddFirendActivity.this.td.getText().toString();
			sharedPreferences =getSharedPreferences(Client.SAVE_USER,MODE_PRIVATE);//获得登录者的信息
			String userid1 = sharedPreferences.getString("userid", ""); 	
			if (soso.length()==0) {
				T.showLong(AddFirendActivity.this, "手机号或昵称不许为空！");
			}else if(userid1.equals(soso) ) {
				T.showLong(AddFirendActivity.this, "不能输入自己的手机号");
			}else {  
				info(userid1,soso);  
			}
			break;
		case R.id.left_change_btn :     
			finish();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		//	String contactsId = this.allContacts.get(position).get("_id").toString() ;  //取得联系人的ID 号 ，从1开始
		Contacts contacts=(Contacts) contactAddAdapter.getItem(position);
		System.out.println("contacts.get_tj_lxr().equals========="+contacts.get_tj_lxr()+"==="+contacts.get_tj_lxr());
		if (contacts.getLxr_name().equals("邀请")) {
			//调用系统发短信
			String message = "朋友们，我用了这款软件觉得挺不错的，日后为了方便我们大家聚会，推荐你们也下载安装下!";
			Uri smsToUri = Uri.parse("smsto:");// 联系人地址 
			Intent intent = new Intent(android.content.Intent.ACTION_SENDTO, smsToUri); 
			intent.putExtra("sms_body",message);// 短信内容 
			startActivity(intent);    
		}else {   
			Intent intent=new Intent(AddFirendActivity.this,AddContactsActivity.class);
			intent.putExtra("lxr_name",contacts.get_tj_lxr());
			startActivity(intent);
			finish();
		}
	}     


	// 获取手机通讯录里的 id ，name  ，以列表的形式显示在手机界面
	public int  myContacts () {
		this.result = super.getContentResolver().query(
				ContactsContract.Contacts.CONTENT_URI, null, null, null, null);	// 查询

		super.startManagingCursor(this.result) ;	// 将结果集交给容器管理

		this.allContacts = new ArrayList<Map<String,Object>>() ;	// 实例化List集合

		for (this.result.moveToFirst(); !this.result.isAfterLast(); this.result
				.moveToNext()) {	// 取出结果集中的每一个内容

			Map<String,Object> contact = new HashMap<String,Object>() ;

			contact.put("_id", this.result.getInt(this.result
					.getColumnIndex(ContactsContract.Contacts._ID)));
			contact.put("name", this.result.getString(this.result
					.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
			this.allContacts.add(contact);
		}
		int max = allContacts.size() ;
		return max ;

	}


	/*    取得联系人的手机号码  ，返回的手机号码
	 * */

	private String getPhoneNumber ( String id) {   //id为联系人的id号 ，从零开始
		String phoneSelection = ContactsContract.CommonDataKinds.Phone.CONTACT_ID
				+ "=?";
		String[] phoneSelectionArgs = new String[] { id };
		Cursor c = super.getContentResolver().query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
				phoneSelection, phoneSelectionArgs, null);

		StringBuffer buf = new StringBuffer() ;     //通过循环迭代把手机号放在StringBuffer中
		for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
			buf.append(
					c.getString(c
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))) ;
		}
		return buf.toString() ;      //返回手机号
	}

	//请求服务器 ，如果数据库中存在，返回1 ，否则返回0
	public void requestServer() {
		final int max = myContacts() ;    // 获取手机通讯录里的 id ，name 
		sharedPreferences =getSharedPreferences(Client.SAVE_USER,MODE_PRIVATE);//获得登录者的信息
		String userid = sharedPreferences.getString("userid", ""); 
		for(int id=0 ; id< max ; id ++) {

			String lxr_name= allContacts.get(id).get("name").toString() ;

			String contactsId = allContacts.get(id).get("_id").toString() ;  //取得联系人的ID 号 ，从1开始
			String phone =  getPhoneNumber(contactsId);
			AjaxParams params = new AjaxParams();
			params.put("userid", phone);
			params.put("login_id", userid);
			params.put("lxr_name", lxr_name);    
			FinalHttp fh = new FinalHttp();  
			fh.post(requestPath, params, new AjaxCallBack<String>() {  
				@Override  
				public void onFailure(Throwable t, String strMsg) {
					System.out.println("加载失败！！！");   
					super.onFailure(t, strMsg);
				}  
				@Override
				public void onLoading(long count, long current) {
					// TODO Auto-generated method stub
					System.out.println("正在加载！！！");
					super.onLoading(count, current);
				}

				@Override  
				public void onSuccess(String jsonString) {
					super.onSuccess(jsonString);

					System.out.println(jsonString+"你还撒旦反间计阿斯海灯法粉红色打法说地方话噶韩国");



				}
			});
		}
	}

}
